package com.xique.door.service.impl;


import com.xique.common.datascope.annotation.NeedSetFieldValue;
import com.xique.common.core.text.Convert;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.request.permissionGroup.*;
import com.xique.door.mapper.PermissionGroupMapper;
import com.xique.door.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限组Service业务层处理
 *
 * @author ww
 * @date 2021-06-11
 */
@Service
public class PermissionGroupServiceImpl implements IPermissionGroupService
{
    @Autowired
    private PermissionGroupMapper permissionGroupMapper;

    @Autowired
    private IPermissionGroupUserService permissionGroupUserService;

    @Autowired
    private IPermissionGroupDeviceService permissionGroupDeviceService;

    @Autowired
    private IAccessDeviceService accessDeviceService;

    @Autowired
    private IPermissionGroupDomainService permissionGroupDomainService;
    /**
     * 查询权限组
     *
     * @param id 权限组ID
     * @return 权限组
     */
    @Override
    public PermissionGroup selectPermissionGroupById(Long id)
    {
        return permissionGroupMapper.selectPermissionGroupById(id);
    }

    /**
     * 查询权限组列表
     *
     * @param permissionGroup 权限组
     * @return 权限组
     */
    @Override
    public List<PermissionGroup> selectPermissionGroupList(PermissionGroup permissionGroup)
    {
        return permissionGroupMapper.selectPermissionGroupList(permissionGroup);
    }

    @Override
    public List<PermissionGroup> selectPermissionGroupListByIds(List<Long> groupIds) {
        if (groupIds.isEmpty()) {
            return new ArrayList<>();
        }
        return permissionGroupMapper.selectPermissionGroupListByIds(groupIds);
    }

    @Override
    public List<PermissionGroup> selectPermissionGroupListByForeignIds(List<Long> ids, String type) {
        if (CollectionUtils.isEmpty(ids) || StringUtils.isEmpty(type)) {
            return new ArrayList<>();
        }

        return permissionGroupMapper.selectPermissionGroupListByForeignIds(ids, type);
    }

    /**
     * 新增权限组
     *
     * @param permissionGroup 权限组
     * @return 结果
     */
    @Override
    public int insertPermissionGroup(PermissionGroup permissionGroup)
    {
        permissionGroup.setCreateTime(DateUtils.getNowDate());
        PermissionGroup search = new PermissionGroup();
        search.setParkId(permissionGroup.getParkId());
        List<PermissionGroup> permissionGroups = permissionGroupMapper.selectPermissionGroupList(search);
        int maxSort = 0;
        if (!permissionGroups.isEmpty()) {
            maxSort = permissionGroups.stream().mapToInt(PermissionGroup::getGroupSort).max().getAsInt();
        }
        if (permissionGroup.getGroupSort() == null){
            permissionGroup.setGroupSort(maxSort + 1);
        }
        return permissionGroupMapper.insertPermissionGroup(permissionGroup);
    }

    /**
     * 修改权限组
     *
     * @param permissionGroup 权限组
     * @return 结果
     */
    @Override
    public int updatePermissionGroup(PermissionGroup permissionGroup)
    {
        permissionGroup.setUpdateTime(DateUtils.getNowDate());
        return permissionGroupMapper.updatePermissionGroup(permissionGroup);
    }

    /**
     * 根据条件分页查询已分配设备权限列表
     *
     * @param request 请求参数
     * @return 权限组设备集合信息
     */
    @Override
    public List<PermissionGroupDevice> selectAllocatedList(PermissionGroupDeviceRequest request) {
        return permissionGroupMapper.selectAllocatedList(request);
    }

    /**
     * 根据条件分页查询未分配设备权限列表
     *
     * @param request 请求参数
     * @return 权限组设备集合信息
     */
    @Override
    public List<PermissionGroupDevice> selectUnallocatedList(PermissionGroupDeviceRequest request) {
        return permissionGroupMapper.selectUnallocatedList(request);
    }

    /**
     * 取消授权设备
     *
     * @param request 权限组何设备关联信息
     * @return 结果
     */
    @Override
    public int deleteDevice(PermissionGroupDeleteDeviceRequest request) {
        //TODO 下发设备信息（删除）
        return permissionGroupDomainService.deleteDevice(request.getGroupId(), Arrays.asList(request.getDeviceId()));
    }

    /**
     * 批量取消授权设备
     *
     * @param request 权限组何设备关联信息
     * @return 结果
     */
    @Override
    public int deleteDevices(PermissionGroupDeleteDeviceRequest request) {
        //TODO 下发设备信息（删除）
        return permissionGroupDomainService.deleteDevice(request.getGroupId(), Arrays.asList(Convert.toLongArray(request.getDeviceIds())));
    }

    /**
     * 根据条件分页查询已分配用户权限列表
     *
     * @param request 请求参数
     * @return 权限组设备集合信息
     */
    @Override
    public List<PermissionGroupUser> selectAllocatedUserList(PermissionGroupUserRequest request) {
        return permissionGroupMapper.selectAllocatedUserList(request);
    }

    /**
     * 根据条件分页查询已分配用户权限列表
     *
     * @param request 请求参数
     * @return 权限组设备集合信息
     */
    @Override
    @NeedSetFieldValue
    public List<PermissionGroupDCard> selectAllocatedDCardList(PermissionGroupUserRequest request) {
        return permissionGroupMapper.selectAllocatedDCardList(request);
    }

    /**
     * 根据条件分页查询未分配用户权限列表
     *
     * @param request 请求参数
     * @return 权限组设备集合信息
     */
    @Override
    public List<PermissionGroupUser> selectUnallocatedUserList(PermissionGroupUserRequest request) {
        return permissionGroupMapper.selectUnallocatedUserList(request);
    }

    /**
     * 取消用户授权设备
     *
     * @param request 权限组何用户关联信息
     * @return 结果
     */
    @Override
    public int deleteUser(PermissionGroupDeleteUserRequest request) {
        //TODO 下发设备信息（删除）
        return permissionGroupDomainService.deleteUser(request.getGroupId(), Arrays.asList(request.getUserId()));
    }

    /**
     * 批量取消用户授权设备
     *
     * @param request 权限组何用户关联信息
     * @return 结果
     */
    @Override
    public int deleteUsers(PermissionGroupDeleteUserRequest request) {
        //TODO 下发设备信息（删除）
        return permissionGroupDomainService.deleteUser(request.getGroupId(), Arrays.asList(Convert.toLongArray(request.getUserIds())));
    }

    @Override
    @Deprecated
    public AjaxResult selectDevices(PermissionGroupSelectDeviceRequest request) {

        List<PermissionGroupUser> userList = permissionGroupUserService.selectPermissionGroupUserListByGroupIds(Collections.singletonList(request.getGroupId()));
        List<Long> userIds = userList.stream().map(PermissionGroupUser::getUserId).collect(Collectors.toList());

        List<Long> devices = Arrays.asList(Convert.toLongArray(request.getDeviceIds()));
        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceByIds(devices);

        List<UserDevice> list = new ArrayList<>();
        userIds.stream().forEach(item -> {
            accessDeviceList.stream().forEach(device -> {
                UserDevice userDevice = new UserDevice();
                userDevice.setParkId(request.getParkId());
                userDevice.setGroupId(request.getGroupId());
                userDevice.setUserId(item);
                userDevice.setDeviceId(device.getId());
                userDevice.setDevSn(device.getDevSn());
                list.add(userDevice);
            });
        });

        List<PermissionGroupDevice> deviceList = new ArrayList<>();
        devices.stream().forEach(item -> {
            PermissionGroupDevice groupDevice = new PermissionGroupDevice();
            groupDevice.setGroupId(request.getGroupId());
            groupDevice.setDeviceId(item);
            deviceList.add(groupDevice);
        });

        int count = permissionGroupDomainService.selectDevice(deviceList, list);
        if (count <= 0) {
            return AjaxResult.error();
        }

        //TODO 下发设备信息

        return AjaxResult.success();
    }

    @Override
    @Deprecated
    public AjaxResult selectUsers(PermissionGroupSelectUserRequest request) {

        List<Long> userIds = Arrays.asList(Convert.toLongArray(request.getUserIds()));
        List<PermissionGroupUser> groupUserList = new ArrayList<>();
        userIds.stream().forEach(item -> {
            PermissionGroupUser groupUser = new PermissionGroupUser();
            groupUser.setGroupId(request.getGroupId());
            groupUser.setUserId(item);
            groupUserList.add(groupUser);
        });

        List<PermissionGroupDevice> deviceList = permissionGroupDeviceService.selectPermissionGroupDeviceListByGroupIds(Collections.singletonList(request.getGroupId()));

        List<UserDevice> list = new ArrayList<>();
        userIds.forEach(item -> {
            deviceList.forEach(device -> {
                UserDevice userDevice = new UserDevice();
                userDevice.setParkId(request.getParkId());
                userDevice.setGroupId(request.getGroupId());
                userDevice.setUserId(item);
                userDevice.setDeviceId(device.getDeviceId());
                userDevice.setDevSn(device.getDevSn());
                list.add(userDevice);
            });
        });

        int count = permissionGroupDomainService.selectUser(groupUserList, list);
        if (count <= 0) {
            return AjaxResult.error();
        }

        //TODO 下发设备信息

        return AjaxResult.success();
    }

    @Override
    public List<PermissionGroup> selectPermissionGroupByUserId(String userId) {
        return permissionGroupMapper.selectPermissionGroupByUserId(userId);
    }
}
